package com.hxh.service;

import com.hxh.entity.ProjectDatasource;
import com.hxh.entity.po.FieldName;
import com.hxh.entity.po.TableInfo;
import com.hxh.util.ConnetMysql;
import com.hxh.util.MysqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.Connection;
import java.util.List;


@Service
@Slf4j
public class TableConfigService {

    public List<TableInfo> getAllTableByDataBaseName(ProjectDatasource projectDatasource, String dataBaseName) throws Exception {
        String sql = "SELECT TABLE_NAME,table_rows,create_time,update_time,table_collation,table_comment FROM information_schema.tables WHERE table_schema= '" + dataBaseName + "'";
        ConnetMysql connetMysql = new ConnetMysql();
        Connection connection = connetMysql.getConnection(projectDatasource);
        List<TableInfo> tableInfos = MysqlUtils.executeOneQuery(connection, sql, TableInfo.class);
        if (!CollectionUtils.isEmpty(tableInfos)) {
            for (TableInfo tableInfo : tableInfos) {
                sql = "show full columns from  `" + tableInfo.getTableName() + "` ;";
                List<FieldName> fieldNameList = MysqlUtils.executeOneQuery(connection, sql, FieldName.class);
                tableInfo.setFieldNames(fieldNameList);
            }
        }
        connection.close();
        return tableInfos;
    }

    public TableInfo getAllTableByDataBaseName(ProjectDatasource projectDatasource, String dataBaseName, String tableName) throws Exception {
        String sql = "SELECT TABLE_NAME,table_rows,create_time,update_time,table_collation,table_comment FROM information_schema.tables " +
                "WHERE table_schema= '" + dataBaseName + "' and TABLE_NAME= '" + tableName + "'";
        List<TableInfo> tableInfos = MysqlUtils.executeOneQuery(projectDatasource, sql, TableInfo.class);
        TableInfo tableInfo = null;
        if (!CollectionUtils.isEmpty(tableInfos)) {
            tableInfo = tableInfos.get(0);
            sql = "show full columns from  " + tableInfo.getTableName() + " ;";
            List<FieldName> fieldNameList = MysqlUtils.executeOneQuery(projectDatasource, sql, FieldName.class);
            tableInfo.setFieldNames(fieldNameList);
        }
        return tableInfo;
    }

    public void deleteTable(ProjectDatasource projectDatasource, String tableName) throws Exception {
        String sql = "DROP TABLE " + tableName + " ;";
        MysqlUtils.executeOneSqlWithException(projectDatasource, sql);
    }


}

